# -*- coding:utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json, time, sys, os, sets, logging
os.sys.path.append('../utils/constants/')
from constants import *
os.sys.path.append('../utils/memcacheDao/')
import memcacheDao
os.sys.path.append('../modules/antispam/')
import antispam
os.sys.path.append('../modules/comment/')
import commentLogic
os.sys.path.append('../modules/user/')
import userLogic
os.sys.path.append('../modules/article/')
import articleLogic
os.sys.path.append('../modules/message/')
import messageLogic

from tornado.options import define, options
reload(sys)  
sys.setdefaultencoding("utf-8")  


class ArticleHandler(tornado.web.RequestHandler):
    def get(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        #print self.get_argument('field')
        ret = {}
        #print strType
        if strType == 'list':
            # 获取列表
            field  = self.get_argument('field', 'creat_time')
            pageno = int(self.get_argument('pageno', 0))
            itype  = int(self.get_argument('itype', 0))
            if field not in sets.Set(['creat_time', 'like_count', 'pv_count', 'today_pv_count', 'comm_count',]):
                field = 'article_id'
            article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
            ret = article_logic.order_by(field, itype, pageno)
            logging.info('t:%s r:%u p:%u i:%u f:%s' % (strType, ret['retcode'], pageno, itype, field,))
        elif strType == 'detail':
            # 获取详细
            article_id = int(self.get_argument('article_id'))
            uip = self.request.remote_ip
            article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
            ret = article_logic.get_detail(article_id, uip)
            logging.info('t:%s r:%u id:%u' % (strType, ret['retcode'], article_id,))
        elif strType == 'comment':
            # 获取评论
            article_id = int(self.get_argument('article_id'))
            pageno     = int(self.get_argument('pageno', 0))
            article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
            ret = article_logic.get_comment(article_id, pageno)
            logging.info('t:%s r:%u id:%u p:%u' % (strType, ret['retcode'], article_id, pageno,))
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
            pass
        self.write(json.dumps(ret))

    def post(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        argument_dict = {}
        ret = {}
        if strType == 'like':
            #argument_dict = self.get_checkin_argument()
            article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
            like_item = {}
            like_item['like'] = 1
            like_item['uip'] = self.request.remote_ip
            like_item['article_id'] = int(self.get_argument('article_id'))
            ret = article_logic.like(like_item)
            logmsg = 't:%s r:%u id:%u ip:%s' % (strType, ret['retcode'], like_item['article_id'], like_item['uip'],)
            # 给用户加活跃值
            if 0 == ret['retcode']:
                string_base64 = self.get_argument('code', '')
                if string_base64 != '':
                    user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
                    checkin_ret = user_logic.checkin(string_base64)
                    logmsg += ' chk:%u' % (checkin_ret['retcode'],)
                    if 0 == checkin_ret['retcode']:
                        user_logic.bonus4ding(checkin_ret['retbody']['user_id'])
                        logmsg += ' bonus ok'
            logging.info(logmsg)
        elif strType == 'ding_cmt':
            #argument_dict = self.get_register_argument()
            article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
            ding_item = {}
            ding_item['uip']   = self.request.remote_ip
            ding_item['thread_id']    = int(self.get_argument('id'))
            ding_item['comment_id']    = int(self.get_argument('cmt_id'))
            # 客户端控制一下，自己不能顶自己
            ret = article_logic.ding_comment(ding_item)
            logmsg = 't:%s r:%u id:%u cid:%u ip:%s' % (strType, ret['retcode'], \
                    ding_item['thread_id'], ding_item['comment_id'], ding_item['uip'],)
            #print '-- ding_comment', ret
            if 0 == ret['retcode']:
                # 给用户加活跃值
                string_base64 = self.get_argument('code', '')
                comment_uid        = int(self.get_argument('cmt_uid'))
                if string_base64 != '':
                    user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
                    checkin_ret = user_logic.checkin(string_base64)
                    logmsg += ' chk:%u' % (checkin_ret['retcode'],)
                    if 0 == checkin_ret['retcode']:
                        #user_logic.bonus4ding(checkin_ret['retbody']['user_id'])
                        user_logic.bonus4ding(checkin_ret['retbody']['user_id'])
                        # 发信通知
                        message_item = {}
                        message_item['recv_uid']   = comment_uid
                        message_item['send_uid']   = int(checkin_ret['retbody']['user_id'])
                        message_item['send_uname'] = checkin_ret['retbody']['user_name']
                        message_item['itype']      = T_ARTICLE_COMMENT_DING
                        message_item['creat_time'] = int(time.time())

                        content = {}
                        content['id']    = ding_item['thread_id']
                        content['title'] = self.get_argument('title')
                        content['cmt']   = self.get_argument('cmt')
                        content['sex']   = checkin_ret['retbody']['sex']
                        message_item['content']    = json.dumps(content)
                        message_logic = messageLogic.messageLogic(self.application.db)
                        mret = message_logic.send(message_item)
                        logmsg += ' msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'],\
                                message_item['send_uid'], message_item['itype'],)
                # 给被顶用户加声望值，缺少一个comment_uid
                #user_logic.bonus4dinged(comment_uid)
                user_logic.bonus4dinged(comment_uid)
                logmsg += ' dcid:%u' % (comment_uid,)
            logging.info(logmsg)
        elif strType == 'post_cmt':
            string_base64 = self.get_argument('code')
            user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
            checkin_ret = user_logic.checkin(string_base64)

            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
                logmsg = 't:%s chk:%u ip:%s' % (strType, checkin_ret['retcode'], self.request.remote_ip,)
            else:
                anti = antispam.antispam(mc.getInstance())
                anti_item = {}
                anti_item['uip']     = self.request.remote_ip
                anti_item['content'] = self.get_argument('reply')
                anti_item['user_id'] = checkin_ret['retbody']['user_id']
                anti_ret = anti.check_repeat(anti_item)

                logmsg = 't:%s chk:%u anti:%u ip:%s uid:%u' % (strType, checkin_ret['retcode'], \
                        anti_ret['retcode'], anti_item['uip'], anti_item['user_id'],)
                if anti_ret['retcode'] != 0:
                    ret = anti_ret
                else:
                    cmt_item = {}
                    # comment中content的格式
                    # 'reply'     -> 回复的内容
                    # 'cmt'       -> 被引用的内容
                    # 'cmt_uid'   -> 被引用的用户id
                    # 'cmt_uname' -> 被引用的用户名
                    #['thread_id', 'comment_uid', 'comment_uname', 'creat_time', 'uip', 'content',]
                    content = {}
                    content['reply']     = self.get_argument('reply')
                    content['cmt']       = self.get_argument('cmt', '')
                    content['cmt_id']    = int(self.get_argument('cmt_id', 0))
                    content['cmt_uid']   = int(self.get_argument('cmt_uid', 0))
                    content['cmt_uname'] = self.get_argument('cmt_uname', '')
                    need_send_message = 0
                    if content['cmt'] == '' or  0 == content['cmt_uid'] or '' == content['cmt_uname']:
                        del content['cmt']
                        del content['cmt_id']
                        del content['cmt_uid']
                        del content['cmt_uname']
                    else:
                        need_send_message = 1

                    cmt_item['content']       = content
                    cmt_item['creat_time']    = int(time.time())
                    cmt_item['uip']           = self.request.remote_ip
                    cmt_item['age']           = int(time.strftime("%Y")) - checkin_ret['retbody']['birth_year']
                    cmt_item['sex']           = checkin_ret['retbody']['sex']
                    cmt_item['phone_type']    = self.get_argument('phone_type')
                    cmt_item['thread_id']     = int(self.get_argument('id'))
                    cmt_item['comment_uid']   = checkin_ret['retbody']['user_id']
                    cmt_item['comment_uname'] = checkin_ret['retbody']['user_name']
                    article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
                    ret = article_logic.add_comment(cmt_item)
                    logmsg += ' r:%u id:%u age:%u sex:%u un:%s nm:%u' % (ret['retcode'], cmt_item['thread_id'],\
                            cmt_item['age'], cmt_item['sex'], cmt_item['comment_uname'], \
                            need_send_message,)
                    if ret['retcode'] == 0:
                        # 为anti设置上刚刚提交的内容，防止重复提交
                        anti.set_content(anti_item)
                        # 给用户加活跃值
                        user_logic.bonus4post_comment(checkin_ret['retbody']['user_id'])

                        if need_send_message:
                            # 发信通知
                            message_item = {}
                            message_item['recv_uid']   = content['cmt_uid']
                            message_item['send_uid']   = int(checkin_ret['retbody']['user_id'])
                            message_item['send_uname'] = checkin_ret['retbody']['user_name']
                            message_item['itype']      = T_ARTICLE_COMMENT_REPLY
                            message_item['creat_time'] = int(time.time())

                            content['id']    = int(self.get_argument('id'))
                            content['title'] = self.get_argument('title')
                            content['sex']   = checkin_ret['retbody']['sex']
                            message_item['content'] = json.dumps(content)
                            message_logic = messageLogic.messageLogic(self.application.db)
                            #print message_logic.send(message_item)
                            mret = message_logic.send(message_item)
                            logmsg += ' msg:%u' % (mret['retcode'],)
            logging.info(logmsg)
        elif strType == 'post_article':
            string_base64 = self.get_argument('code')
            user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
            checkin_ret = user_logic.checkin(string_base64)

            anti = antispam.antispam(mc.getInstance())
            anti_item = {}
            anti_item['uip']     = self.request.remote_ip
            anti_item['content'] = self.get_argument('title')
            anti_ret = anti.check_repeat(anti_item)

            logmsg = 't:%s chk:%u anti:%u ip:%s' % (strType, checkin_ret['retcode'], \
                    anti_ret['retcode'], anti_item['uip'],)

            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
            elif anti_ret['retcode'] != 0:
                ret = anti_ret
            else:
                article_item = {}
                article_item['title']      = self.get_argument('title').encode('utf8').replace(' ', '')
                article_item['content']    = self.get_argument('content').encode('utf8').replace(' ', '')
                article_item['summary']    = self.get_argument('summary').encode('utf8').replace(' ', '')
                article_item['imgurl']     = self.get_argument('img_url').encode('utf8').replace(' ', '')
                #article_item['tags']       = self.get_argument('tags', '').encode('utf8')
                article_item['itype']      = int(self.get_argument('itype'))
                article_item['creat_time'] = int(self.get_argument('creat_time', time.time()))
                #print 'content', len(article_item['content'])
                article_logic = articleLogic.articleLogic(self.application.db, mc.getInstance())
                ret = article_logic.add(article_item)
                logmsg += ' r:%u' % (ret['retcode'], )
                if 0 == ret['retcode']: anti.set_content(anti_item)
            logging.info(logmsg)
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        #print ret
        self.write(json.dumps(ret))
